package com.example.dongshihao.startproject_211dsh.model;

import com.example.dongshihao.startproject_211dsh.MainActivity;
import com.example.dongshihao.startproject_211dsh.bean.WeatherResult;
import com.example.dongshihao.startproject_211dsh.iface.WeatherListener;
import com.example.dongshihao.startproject_211dsh.iface.Weatheriface;
import com.example.dongshihao.startproject_211dsh.service.Weather51Service;

import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by dongshihao on 17/3/14.
 */

public class Weather51Model implements Weatheriface {

    private Retrofit retrofit;
    private String BASEURL = "http://weather.51wnl.com/weatherinfo/";
    private Weather51Service weather51Service;

    public Weather51Model() {
        System.out.println("---Weather51Model");
        retrofit = new Retrofit.Builder().baseUrl(BASEURL)
                .addConverterFactory(GsonConverterFactory.create()).build();
    }


        @Override
        public void getWeather (String cityCode,final WeatherListener weatherListener){
            System.out.println("---getWeather");
            //2
            weather51Service = retrofit.create(Weather51Service.class);
            Call<WeatherResult> call = weather51Service.getResult(cityCode, 1);
            //3
            call.enqueue(new Callback<WeatherResult>() {
                @Override
                public void onResponse(Call<WeatherResult> call, Response<WeatherResult> response) {
                    //WeatherListener listener;
                    System.out.println("---onResponse");
                    if (response.isSuccessful() && response.body() != null)
                        weatherListener.onRespense(response.body().getWeatherinfo());
                    else
                        weatherListener.onFail("onresponse fail");
                }

                @Override
                public void onFailure(Call<WeatherResult> call, Throwable t) {
                    System.out.println("---onFailure");
                    weatherListener.onFail(t.toString());

                }
            });
        }
}

